#!/usr/bin/perl
# to select the overlap portion of 1_flow_table.csv, in particular, when sending rate of flow1 > flow

#folders
$root_folder="/root/switch_project";
$result_folder="$root_folder/experiment/exp16"; #root dir to store experimental resutls


$runs=2; # number of repeated experiment (same setting)
$extra_num_packets=50; # number of extra packets to include (ensure all overlap is included)

@speed;

#specify sending rate
$start_sending_rate=100;#Mb/s
$end_sending_rate=1000;
$sending_rate_gap=100;

#calculate speed and gap (gap is not used for now)
for($b=$start_sending_rate, $a=0; $b<=$end_sending_rate; $b+=$sending_rate_gap, $a++)
{
	$speed[$a]=$b;
}


for($j=0; $j<=$#speed; $j++)
{
	for($k=0; $k<=$#speed; $k++)
	{
		for($i=1; $i<=$runs; $i++)
		{	
			chdir "$result_folder/$speed[$j]M/$speed[$k]M/$i";
			print "folder = $result_folder/$speed[$j]M/$speed[$k]M/$i\n";

			$input = "1_flow_table.csv";
			$output = "1_flow_table_overlap.csv";
	
			if($speed[$j] >= $speed[$k])
			{
				system("cp $input $output");
			}
			else
			{				
				$first_line=`head -n 1 $result_folder/$speed[$k]M/$speed[$j]M/$i/$input`;
				print("$first_line\n");
				@first_line_block=split(', ', $first_line);
				$last_line=`tail -n 1 $result_folder/$speed[$k]M/$speed[$j]M/$i/$input`;
				print("$last_line\n");
				@last_line_block=split(', ', $last_line);

				$duration = $last_line_block[2] - $first_line_block[2];
				print("[$speed[$j]M - $speed[$k]M] duration of flow2: $duration\n");
				
				open(INPUT1, $input) or die "$input cannot be opened.\n";
				open(OUTPUT1, ">$output") or die "$output cannot be created.\n";
				
				$line1=`head -n 1 $result_folder/$speed[$j]M/$speed[$k]M/$i/$input`;
				print("$line1\n");
				@line1=split(', ', $line1);
				$start = $line1[2];
				$end = $start+$duration;
				print("flow1: start = $start, end = $end\n");

				$extra_pkt_counter=0;
				while(<INPUT1>)
				{
					$line=$_;
					chomp($line);
					@block = split(", ", $line);
						
					if($block[2] <=$end)
					{
						print OUTPUT1 "$line\n";
					}
					elsif($extra_pkt_counter < $extra_num_packets)
					{
						print OUTPUT1 "$line\n";
						$extra_pkt_counter+=1;
					}
					else
					{
						last;
					}
				}				
					
				close(INPUT1);
				close(OUTPUT1);
			}
		}
	}
}

chdir "$root_folder/script";
